﻿using System;
using System.IO;

namespace TY.UT.Pay.WxPay.lib
{
    public class Log
    {
        //在网站根目录下创建日志目录
        private static readonly string Path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");

        /// <summary>
        /// 向日志文件写入调试信息
        /// </summary>
        /// <param name="className"></param>
        /// <param name="content"></param>
        public static void Debug(string className, string content)
        {
            if (WxPayConfig.LogLevenl >= 3)
            {
                WriteLog("DEBUG", className, content);
            }
        }

        /// <summary>
        /// 向日志文件写入运行时信息
        /// </summary>
        /// <param name="className"></param>
        /// <param name="content"></param>
        public static void Info(string className, string content)
        {
            if (WxPayConfig.LogLevenl >= 2)
            {
                WriteLog("INFO", className, content);
            }
        }

        /// <summary>
        ///  向日志文件写入出错信息
        /// </summary>
        /// <param name="className"></param>
        /// <param name="content"></param>
        public static void Error(string className, string content)
        {
            if (WxPayConfig.LogLevenl >= 1)
            {
                WriteLog("ERROR", className, content);
            }
        }

        /// <summary>
        /// 实际的写日志操作
        /// </summary>
        /// <param name="type"></param>
        /// <param name="className"></param>
        /// <param name="content"></param>
        private static void WriteLog(string type, string className, string content)
        {
            if (!Directory.Exists(Path)) //如果日志目录不存在就创建
            {
                Directory.CreateDirectory(Path);
            }

            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); //获取当前系统时间
            string filename = Path + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; //用日期对日志文件命名

            //创建或打开日志文件，向日志文件末尾追加记录
            StreamWriter mySw = File.AppendText(filename);

            //向日志文件写入内容
            string writeContent = time + " " + type + " " + className + ": " + content;
            mySw.WriteLine(writeContent);

            //关闭日志文件
            mySw.Close();
        }
    }
}